let fs = require('fs');


let dataFn = {
    // file文件名 obj写入的数据对象
    // 通过promise写入数据  
    // 2. resolved : 成功状态; 
    // 3. rejected : 失败状态; 
    

    writeFileData: (filename, obj) => {
        let promise = new Promise((resolve, reject) => {
            obj = JSON.stringify(obj);
            fs.writeFile("./data/" + filename, obj,err=>{
                if (err) {
                    reject("fail " + err);
                }
                else {
                    // resolve("write success!");
                    resolve(obj);
                }
            });
        })
        return promise;
    },
    // filename文件名 promise对象
    readFileData: (filename) => {
        let promise = new Promise((resolve, reject) => {
            fs.readFile("./data/" + filename, "utf-8", (err, data) => {
                if (err) {
                    console.log(err);
                    reject("read filedata error!");
                } else {
                    // data = JSON.parse(data);
                    resolve(data);
                }
            })
        });
        return promise;
    }
};


module.exports = dataFn;

  
 
  dataFn.writeFileData('2.txt',{koko:'如果有那也是他想让你知道'}).then(data=>{
      console.log(data );
  })
  dataFn.readFileData('1.txt').then(data=>{
      console.log(data);
  })
  